package com.example.demo.common.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.text.NumberFormat;

/**
 * 源数据金额单位: 元
 * 支持类型: ? extends Number
 *
 *         0 --> ￥0.00
 * 100000000 --> ￥1,000,000.00
 * 123456789 --> ￥1,234,567.89
 *
 * PS:
 * ✅ #,##0.00
 * ❌ #,###.##
 *
 * @author Shanks
 * @date 2020-11-07
 */
public class YuanCurrencySerializer extends JsonSerializer<Number> {

    @Override
    public void serialize(Number number, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        // 获取当前货币格式化实例
        NumberFormat numberFormat = NumberFormat.getCurrencyInstance();
        // 设置小数部分所允许的最少位数(如果不足后面补0)
        numberFormat.setMinimumFractionDigits(2);
        // 设置小数部分所允许的最多位数(如果超过会四舍五入)
        numberFormat.setMaximumFractionDigits(3);
        jsonGenerator.writeString(numberFormat.format(number));
    }
}